package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: 刘安杰
 * @Date: 2024/8/20
 * @Time: 16:30
 * @Description:
 */
//判断用户是否登录的拦截器
    @Component
public class AuthenticationInterception implements HandlerInterceptor {
        //处理请求之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     //获取请求头中的token
        String token = request.getHeader("access-token");
        if (!StringUtils.hasLength(token)){
            //证明没有登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        //解析token
        Claims claims = JwtUtil.parseToken(token);
        //获取用户id
        Long userId = claims.get("userId",Long.class);
        //获取用户名
        String username = claims.get("username", String.class);
        //创建LonginUser对象
        LoginUser loginUser = new LoginUser(userId, username);
        //将loginUser放到当前线程中
        LoginUserContext.setLoginUser(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //将LoginUser对象从当前线程中移除
        LoginUserContext.removeLoginUser();
    }
}
